package com.gitee.dupe.oauth.granter;

import cn.hutool.core.util.StrUtil;
import com.gitee.dolt.boot.decrypt.PasswordEncoder;
import com.gitee.dolt.core.exception.BizException;
import com.gitee.dolt.core.exception.code.ExceptionCode;
import com.gitee.dolt.core.util.BizAssert;
import com.gitee.dolt.security.model.AuthInfo;
import com.gitee.dolt.security.token.TokenProvider;
import com.gitee.dupe.authority.entity.User;
import com.gitee.dupe.authority.service.IResourceService;
import com.gitee.dupe.authority.service.IRoleService;
import com.gitee.dupe.authority.service.IUserService;
import com.gitee.dupe.common.captcha.CaptchaService;
import com.gitee.dupe.oauth.dto.LoginDTO;
import org.springframework.stereotype.Component;

/**
 * @author LYH
 */
@Component(PasswordTokenGranter.GRANT_TYPE)
public class PasswordTokenGranter extends AbstractTokenGranter {


    public static final String GRANT_TYPE = "PASSWORD";

    private PasswordEncoder passwordEncoder;
    private final IUserService userService;
    private final CaptchaService captchaService;

    public PasswordTokenGranter(PasswordEncoder passwordEncoder, IUserService userService, CaptchaService captchaService, TokenProvider tokenProvider,
                                IRoleService roleService, IResourceService resourceService) {
        super(tokenProvider, roleService, resourceService);
        this.passwordEncoder = passwordEncoder;
        this.userService = userService;
        this.captchaService = captchaService;
    }

    @Override
    public AuthInfo grant(LoginDTO loginDTO) {
        captchaService.checkCaptchaAndRemove(loginDTO.getKey(), loginDTO.getCode());
        String loginName = loginDTO.getLoginName();
        String password = loginDTO.getPassword();
        BizAssert.isTrue(StrUtil.isAllNotEmpty(loginName, password), "loginName/password不能为空");
        User userByAccount = userService.getOneByAccount(loginName);
        if (userByAccount == null || !passwordEncoder.matches(password, userByAccount.getPasswordHash())) {
            throw new BizException(ExceptionCode.JWT_USER_INVALID);
        }
        AuthInfo authInfo = createAuthInfo(userByAccount);
        return authInfo;
    }
}
